package com.by.hazelcasttopic.annotation;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.by.toolkitspring.customizeannotation.AbstractByAnnotationContext;
import com.by.toolkitspring.customizeannotation.ByAnnotationProcessor;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用于接收负责监听广播消息的监听者信息
 *
 * @author YanBingHao
 * @since 2025/3/19
 */
@Slf4j
public class HazelcastTopicListenerContext implements AbstractByAnnotationContext<HazelcastTopicListener> {

    private static final Map<String, Class<?>> TAG_PROCESSER_MAP = Maps.newHashMap();
    private static final Map<String, Class<?>> TAG_ARG_MAP = Maps.newHashMap();

    @Override
    public void receiveContext(List<ByAnnotationProcessor.CustomizeAnnotationInfo> infos) {
        if (CollectionUtils.isEmpty(infos)) {
            return;
        }

        TAG_PROCESSER_MAP.putAll(infos.stream()
                .collect(Collectors.toMap(i -> {
                    HazelcastTopicListener subscriber = (HazelcastTopicListener) i.getAnnotationInfo();
                    return subscriber.value();
                }, ByAnnotationProcessor.CustomizeAnnotationInfo::getBeanClass)));

        TAG_ARG_MAP.putAll(infos.stream()
                .collect(Collectors.toMap(i -> {
                    HazelcastTopicListener subscriber = (HazelcastTopicListener) i.getAnnotationInfo();
                    return subscriber.value();
                }, i -> ClassUtil.getTypeArgument(i.getBeanClass()))));
    }


    public <T> AbstractHazelcastTopicListener<T> get(String tag) {
        Class<?> aClass = TAG_PROCESSER_MAP.get(tag);
        if (Objects.isNull(aClass)) {
            return null;
        }
        return (AbstractHazelcastTopicListener<T>) SpringUtil.getBean(aClass);
    }

    public Class<?> getArgClass(String tag) {
        return TAG_ARG_MAP.get(tag);
    }

}
